import * as API_AfterSale from '../../../../api/after-sale.js';
import {Foundation} from '../../../../ui-utils/index.js';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_sn: '',
    sku_id: '',
    order: '', // 订单详情
    skuList: [], // 货品列表
    type: 'money',// 申请售后类型
    refund_reason: '',
    customer_remark: '',
    isCancel: false, // 是否为取消订单模式
    reasonList: [ '我不想买了', '地址信息填错', '商品选错了', '其他' ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { order_sn, type, sku_id } = options;
    this.setData({ 
      order_sn: order_sn,
      sku_id: sku_id || '',
      isCancel: type === 'cancel'
    });
    this.getAfterSaleData()
  },
  // 获取售后数据
  getAfterSaleData(){
    API_AfterSale.getAfterSaleData(this.data.order_sn,this.data.sku_id).then(response=>{
      this.setData({
        order: response.order
      });
      if(response.sku_list && response.sku_list.length){
        response.sku_list.forEach(item => {
          if (!item.skuName) item.skuName = this.formatterSkuSpec(item)
          item.purchase_price = Foundation.formatPrice(item.purchase_price)
        })
      }
      this.setData({
        skuList: response.sku_list,
      })
    })
  },
  /** 规格格式化显示 */
  formatterSkuSpec(sku) {
    if (!sku.spec_list || !sku.spec_list.length) return ''
    return sku.spec_list.map(spec => spec.spec_value).join(' - ')
  },
  // 售后类型选择
  changeType(e) {
    this.setData({ 'type': e.detail.value });
  },
  // 申请原因选择
  changeReason(e) {
    this.setData({ 'refund_reason': e.detail.value });
  },
  // 申请备注
  changeRemark(e) {
    this.setData({ 'customer_remark': e.detail.value });
  },
  // 提交申请
  submitForm() {
    const { order_sn, isCancel, type, refund_reason, customer_remark } = this.data;
    if(!refund_reason){
      wx.showToast({title: '请选择申请原因',icon:'none'})
      return false
    };
    let params = {
      refund_reason,
      customer_remark,
      order_sn
    };
    params.sku_id = this.data.sku_id || '';
    // applyAfterSaleGoods: 申请退货;applyAfterSaleMoney: 退款；applyAfterSaleCancel: 取消
    let _serviceName = API_AfterSale.applyAfterSaleGoods;
    if (type === 'money') {
      _serviceName = isCancel ? API_AfterSale.applyAfterSaleCancel : API_AfterSale.applyAfterSaleMoney;
    };
    _serviceName(params).then(() => {
      // 调用消息订阅提示[RETUND_NOTICE_1：订单售后审核通知]
      app.sendNotice('RETUND_NOTICE_1');
      setTimeout(() => {
        wx.navigateBack({ delta: 1 });
        wx.showToast({ title: '申请成功' });
      }, 1000);
    });
  }
})